import collections
class Solution(object):
    def numEnclaves(self, grid):
        alset = set()
        m = len(grid)
        n = len(grid[0])
        ans = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j] and (i, j) not in alset:
                    count = 1
                    flag = False
                    now = collections.deque([(i, j)])
                    alset.add((i, j))
                    while now:
                        x, y = now.popleft()
                        for ux, uy in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
                            if 0 <= ux < m and 0 <= uy < n:
                                if grid[ux][uy] and (ux, uy) not in alset:
                                    count += 1
                                    alset.add((ux, uy))
                                    now.append((ux, uy))
                            else:
                                flag = True
                    if not flag:
                        ans += count
        return ans